package com.self.springframework.beans.factory.support;

import com.self.springframework.beans.factory.DisposableBean;
import com.self.springframework.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    protected static final Object NULL_OBJECT = new Object();
    private final Map<String,Object> singletObjects = new HashMap<>();
    private final Map<String, DisposableBean> disposableBeans = new HashMap<>();

    @Override
    public Object getSingleton(String beanName) {
        return singletObjects.get(beanName);
    }

    @Override
    public void registerSingleton(String beanName, Object singletonObject) {
        singletObjects.put(beanName,singletonObject);
    }

    protected void addSingleton(String beanName,Object singletonObject){
        singletObjects.put(beanName,singletonObject);
    }

    public void registerDisposableBean(String beanName,DisposableBean bean) {
        this.disposableBeans.put(beanName, bean);
    }

    public void destroySingletons() {
        Set<String> keySet = this.disposableBeans.keySet();
        Object[] disposableBeanNames = keySet.toArray();
        for (Object name : disposableBeanNames) {
            DisposableBean disposableBean = disposableBeans.remove(name);
            disposableBean.destroy();
        }
    }
}
